<template>
  <div>
    <DatetimePicker v-if="edit===true"
                    :key="field.name"
                    v-model="localtime"
                    type="date"
                    :title="field.title"
                    :required="field.required || false"
                    value-text-align="left"
                    align="left"
                    @change="onchange"
    />
    <div v-else>{{value.cval}}</div>
  </div>
</template>
<script>
  import moment from 'moment-timezone'
  import gql from 'graphql-tag'
import { DatetimePicker } from 'vant';
  export default {
    name: 'FieldDate',components: {DatetimePicker},
    props: {
      field: {
        type: Object,
        default() {
          return {}
        }
      },

      saveFast: {type: Boolean, defautl: true},
      model: {type: String, default: ''},
      id: {type: Number, default: 0},
      edit: {type: Boolean, defautl: false}
    },
    data() {
      return {localtime: '-'}
    }, inject: ['value'],
    mounted: function () {
      this.localtime = new Date(this.value.cval)
    },
    computed: {
      displaytime() {
        if (this.value.cval) {
          let t = new Date(this.value.cval)
          return t
        }
        return '-'
      },

      writeDict() {
        let v = {}
        v[this.field.name] = this.newval
        return v
      }
    },
    watch: {
      localtime(to, from) {
        let myTime = moment.tz(to, 'Asia/Shanghai')
        let myTimeUTC = myTime.clone().tz('UTC')
        this.value.newval = myTimeUTC
        this.$emit('update:value', this.value)
      }
    },
    methods: {
      onchange: function (val) {
        if (this.saveFast) {
          this.$apollo.mutate({
            mutation: gql`mutation($id:Int!,$model:String!,$value:JSON!){
  writeRecord(id:$id,model:$model,value:$value){
    ok
  }
}`,
            variables: {id: this.id, model: this.model, value: this.writeDict}
          }).then(function (response) {
            if (response && response.data.writeRecord.ok) {
              // self.app_root.toast(response.result.errMsg)
              // self.$router ? self.$router.back() : window.history.back()
            } else if (response && !response.data.writeRecord.ok) {
              // self.app_root.toast(response.result.errMsg)
            }
          })
            .catch(function (error) {
              console.log(error, __filename)
            })
        } else {
          // this.value.value = this.pvalue
          this.$emit('update:value', this.value)
        }
      }
    }
  }
</script>

<style scoped>

</style>
